package com.example.common.recycler.common;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.example.common.recycler.base.BaseBindView;
import com.example.common.recycler.base.BindViewStore;
import com.example.common.recycler.base.IBIndViewManager;

import java.util.List;

/**
 *
 * @param <T> item类
 */
public class CommonBindViewManager<T> implements IBIndViewManager<T, RecyclerViewHolder, BaseCommonBindView<T>> {
    private BindViewStore<BaseCommonBindView<T>> bindViewStore = new BindViewStore<>();

    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(getItemView(parent, viewType));
        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position, @NonNull T t, @NonNull List<Object> payloads) {
        bindViewStore.getBindView(t.getClass().hashCode()).bindViewData(holder, position, t, payloads);
    }

    @Override
    public void onViewRecycled(@NonNull RecyclerViewHolder holder, @NonNull T t) {
        int code = t.getClass().hashCode();
        BaseBindView bindView = bindViewStore.getBindView(code);
        if (bindView == null) {
            return;
        }
        bindView.onViewRecycled(holder);
    }

    @Override
    public void register(@NonNull BaseCommonBindView bindView) {
        bindViewStore.putBindView(bindView.itemBeanType.hashCode(), bindView);
    }

    public View getItemView(@NonNull ViewGroup parent, int viewType) {
        return LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
    }

    @Override
    public int getItemViewType(int position, @NonNull T t) {
        int type = t.getClass().hashCode();
        int resId = bindViewStore.getBindView(type).getItemLayoutResId(t);
        return resId;
    }
}
